<template>
    <div class="content-box">
      <div ref="searchBox" class="search-box flex" v-show="showSearch">
         <el-button
           type="primary"
           icon="el-icon-search"
           size="mini"
           @click="handleQuery"
           >查询</el-button
         >
         <el-button
           type="warning"
           icon="el-icon-edit-outline"
           size="mini"
           v-hasPermi="['customer:showService:editStatus']"
           @click="handelDialog('编辑状态')"
           >编辑状态</el-button
         >
      </div>
  
      <div class="table-box">
        <el-row :gutter="10" class="mb8">
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="handleQuery"
            :columns="columns"
          ></right-toolbar>
        </el-row>
        <el-table
          v-sticky-header
          ref="table"
          v-loading="loading"
          :data="dataList"
        >
          <template v-for="(item,index) in columns">
            <el-table-column
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :width="getColumnWidth(index)"
              align="center"
              :fixed="item.fixed"
              :sortable="item.sortable ? item.sortable : false"
              :show-overflow-tooltip="item.showTooltip"
              v-if="item.visible"
            >
            <template slot-scope="scope">
              <el-button
                  v-if="item.prop =='url' && scope.row[item.prop]"
                  slot="reference"
                  type="text"
                  v-hasPermi="['customer:showService:remove']"
                  @click="handTipPopup(scope.row)"
                  ><span style="color: #ff116e">
                    {{ scope.row[item.prop] }}
                  </span></el-button
                >
              <template v-else>
                {{ scope.row[item.prop] }}
              </template>
            </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
     <!-- 编辑 对话框 -->
     <el-dialog
      :title="title"
      width="600px"
      :visible.sync="dialogShow"
      :before-close="handleClose"
     >
     <el-form :model="form" :rules="rules" label-width="120px" ref="formRef">
         <el-form-item
            label="状态"
            prop="status"
          >
            <el-radio-group 
                @change="changeStatus"
                v-removeAriaHidden v-model="form.status" >
                <el-radio 
                 v-for="(item,index) in statusOption" 
                 :key="index" 
                 :label="item.value">
                 {{ item.label }}
                </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
             label="查询时间"
             prop="dateRange"
             v-if="form.status"
           >
             <el-date-picker
               clearable
               v-model="dateRange"
               type="datetimerange"
               range-separator="至"
               value-format="yyyy-MM-dd HH:mm:ss"
               start-placeholder="开始时间"
               end-placeholder="结束时间"
             >
             </el-date-picker>
           </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" >
          <el-button type="primary" @click="handleSubmit('formRef')"
            >确 定</el-button
          >
          <el-button @click="handleClose">取 消</el-button>
        </div>
     </el-dialog>
     <el-dialog
      title="是否关闭"
      :visible.sync="infoDialogShow"
      width="480px"
      :before-close="handleTipClose">
        <!-- 使用 iframe 嵌套外部页面 -->
        <iframe
          :src="infoTextObj.url"
          width="100%"
          height="580px" 
          frameborder="0"
          style="border:none;font-size: 14px;"
        ></iframe>
        <span slot="footer" class="dialog-footer">
          <el-button @click="infoDialogShow = false">关闭</el-button>
          <!-- <el-button type="primary" @click="handelDel">确 定</el-button> -->
        </span>
     </el-dialog>


    </div>
  </template>
  
  <script>
  import tableStickyMixins from "@/mixins/tableStickyMixins";
  import { mapGetters } from "vuex";
  import { deleteById, selectAll,editStatus,getStatus} from "@/api/customer/showService";
  
  export default {
    // 定义名字用于标识该组件是否被keep-alive缓存
    name: "ShowService",
    data() {
      // 时间的检验
      const timeValidatePass=(rule, value, callback)=>{
          if (this.dateRange == null || this.dateRange?.length == 0) {
            callback(new Error('请选择查询时间'));
          } else {
            callback();
          };
      };
      return {
        // 数据列表
        dataList: [],
        loading: false,
        // 表格列信息
        columns: [
          {label: `订单号`,prop: "orderId",visible: true,pcWidth: 220,mobileWidth: 150,fixed: null,showTooltip: true,},
          {label: `手机号MD5`,prop: "phoneMd5",visible: true,pcWidth: 220,mobileWidth: 150,fixed: null,showTooltip: true,},
          {label: `产品名称`,prop: "productName",visible: true,pcWidth: 180,mobileWidth: 150,fixed: null,showTooltip: true,},
          {label: `产品地址`,prop: "url",visible: true,pcWidth: 'auto',mobileWidth: 180,fixed: null,showTooltip: true,},
          {label: `创建时间`,prop: "createTime",visible: true,pcWidth: 220,mobileWidth: 180,fixed: null,showTooltip: true,},
        ], 
        // 显示搜索栏
        showSearch: true,
        // 弹框标题
        title: "",
        // 弹框显示状态
        dialogShow: false,
        // 弹框的表单信息
        form: {
          status:0
        },
        // 弹框表单校验规则
        rules: {
          dateRange:[
            { required: true,validator: timeValidatePass, message: "请选择时间范围", trigger: "change" },
          ],
        },
        // 时间范围
        dateRange: [],
        // 状态筛选项
        statusOption: [
          { value: 0, label: "关闭" },
          { value: 1, label: "开启" },
        ],
        // 定时器对象
        timer:null,
        // 文本信息弹框
        infoDialogShow:false,
        // 文本信息对象
        infoTextObj: {},

      };
    },
    mixins: [tableStickyMixins],
    watch: {
      columns: {
        handler() {
          this.updateTableHeight();
        },
        deep: true,
      },
    },
    created() {
      this.getList();
      // 5s 刷新一次
      this.timer = setInterval(() => {
        this.getList();
      }, 5000); 
    },
    computed: {
      ...mapGetters(["sidebar", "device"]),
      // 计算当前列元素在所处环境的宽度
      getColumnWidth() {
        return (index) => {
          return this.isMobile
            ? this.columns[index].mobileWidth
            : this?.sidebar?.opened
            ? this.columns[index].pcWidth - this.slightWidth
            : this.columns[index].pcWidth + 17;
        };
      },
    },
    activated(){
      // 如果再次进入清空
      this.timer && clearInterval(this.timer);
      // 5s 刷新一次
      this.timer = setInterval(() => {
        this.getList();
      }, 5000); 
      console.log('被激活');
      
    },
    deactivated(){
      console.log('失活');
      // 清空定时器
      this.timer && clearInterval(this.timer);
    },
    beforeDestroy() {
      this.timer && clearInterval(this.timer);
    },
    methods: {
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        selectAll().then((response) => {
          // 解决id为number类型精度丢失问题
          this.dataList = response?.data?.map((row) => {
            return {
              ...row,
              id: row.id.toString(),
            };
          });
          this.loading = false;
        }).catch((err) => {
          setTimeout(() => {// 延迟2s后自动取消加载状态
            this.loading = false;
          }, 2000);
        })
      },
      // 修改表格高度触发回调
      updateTableHeight() {
        this.$nextTick(() => {
          this.$refs.table.doLayout();
        });
      },
      // 切换状态项
      changeStatus(){
        this.$set(this,'dateRange',null)
        this.$set(this.form,'startTime',null)
        this.$set(this.form,'endTime',null)
      },
      // 操作文本弹框
      handTipPopup(row){
          this.infoDialogShow = true
          this.$set(this,'infoTextObj',row)
          // 直接删除
          this.handelDel()
      },
      // 关闭文本弹框
      handleTipClose(){
        this.infoDialogShow = false
      },
      // 删除列表项
      handelDel() {
        deleteById(this?.infoTextObj?.id).then((res) => {
          if (res.code === 200) {
            this.$message.success("删除成功");
            // this.getList();
            // this.handleTipClose()
          }
        });
  
      },
       // 处理对话框
      handelDialog(title) {
        // 获取当前的状态
        this.getCurrentStatus();
        // 赋值标题和对话框状态
        this.title = title;
        this.dialogShow = true;
      },
      getCurrentStatus(){
        getStatus().then(res=>{
          if(res.code===200){
            let {startTime,endTime} = res?.data || null
            this.$set(this,'form',{
               ...res?.data,
            })
            if(startTime){
              this.$set(this,'dateRange',[startTime,endTime])
            }else{
              this.$set(this,'dateRange',null)
            }
          }
        })
      },
      /*关闭弹窗*/
      handleClose() {
        this.$refs["formRef"].resetFields();
        this.form = this.$options.data().form;
        this.dialogShow = false;
      },
      /*提交操作*/
      handleSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let params = {};
            params = JSON.parse(JSON.stringify(this.form));
            if (this.dateRange?.length) {
              params.startTime = this.dateRange[0];
              params.endTime = this.dateRange[1];
            }else{
              delete params.startTime
              delete params.endTime
            }
            console.log(params);
            editStatus(params).then((res) => {
              if (res.code === 200) {
                this.$message.success("操作成功");
                this.getList();
                this.handleClose();
               }
            })
            
          }
        })
      }
     
    },
  };
  </script>
  
  <style scoped lang="scss">
  .title {
    font-size: 20px;
    color: #333333;
    font-weight: 500;
  }
  .search-box {
    margin: 0 0 20px;
    padding: 20px;
    background: #fff;
    align-items: flex-start;
    border-radius: 6px;
  }
  .search-area {
    position: absolute;
    right: 20px;
  }
  .el-form-item__content {
    flex: 1;
    line-height: 40px;
    position: relative;
    font-size: 14px;
    min-width: 0;
  }
  ::v-deep .el-dialog__body {
    border-top: 1px solid #dfe6ec;
    border-bottom: 1px solid #dfe6ec;
  }
  .el-table {
    // 滚动条加粗
    --scrollbar-height: 9px;
  }
  </style>
  